from datetime import datetime

from django.contrib.auth.models import AbstractUser
from django.db import models

from model.models import Point


class User(AbstractUser):
    """ Custom User Model Class """

    class Meta:
        db_table = 'user'
        verbose_name = 'user'
        verbose_name_plural = verbose_name

    class Role(models.IntegerChoices):
        """ Role-Permission """
        person = 1
        admin = 2
        super_admin = 3

    class Status(models.IntegerChoices):
        """ The apply status of the admin """
        normal = 1
        applying = 2
        apply_approve = 3
        apply_not_approve = 4

    uid = models.AutoField(
        verbose_name='The unique ID of the user',
        primary_key=True
    )
    phone = models.CharField(
        verbose_name='The phone number of the user',
        max_length=20, default=None, null=True
    )
    last_login = models.DateTimeField(
        verbose_name='The last login time of the user',
        default=None, null=True
    )
    longitude = models.DecimalField(
        verbose_name='The last login Longitude of the user',
        max_digits=12, decimal_places=8, default=None, null=True
    )
    latitude = models.DecimalField(
        verbose_name='The last login Latitude of the user',
        max_digits=12, decimal_places=8, default=None, null=True
    )
    role = models.IntegerField(
        verbose_name='User Role Permission',
        choices=Role.choices, default=Role.person, null=False
    )
    status = models.IntegerField(
        verbose_name='Admin apply status',
        choices=Status.choices, default=Status.normal, null=False
    )

    def info(self):
        return {
            'uid': self.uid,
            'username': self.username,
            'phone': self.phone,
            'last_login': self.last_login,
            'longitude': self.longitude,
            'latitude': self.latitude,
            'role': self.role,
            'status': self.status
        }

    def pointStatistics(self):
        """ Statistics on the number of user upload points """
        return {
            'point': {
                'person': self.point_set.filter(type=Point.Type.person).count(),
                'share': self.point_set.filter(type=Point.Type.share).count()
            }
        }

    def update_login_time(self):
        self.last_login = datetime.now()
        self.save()

    def update_location(self, longitude, latitude):
        self.longitude = longitude
        self.latitude = latitude
        self.save()

    def set_role(self, role):
        self.role = role
        self.save()

    def set_status(self, status):
        self.status = status
        self.save()
